/**
 * Created by charsen on 16/5/26.
 */
directives.directive('fieldList', ["$rootScope", "$routeParams", "tools", "$timeout", function ($rootScope, $routeParams, tools, $timeout) {
    return {
        restrict: 'AE',
        scope: {
            menu: '=json'
        },
        replace: true,
        link: function (scope, element, attr) {
            var tableType = $routeParams.tableType;
            var tbId = $routeParams.tbId;
            var selected_type = "";
            var events = {};

            $(element).css({
                height: document.documentElement.clientHeight - 90 + 'px'
            });

            scope.fields = {
                dimensionality2: [],
                dimensionality: [],
                measurement2: [],
                measurement: [],
                condition: [],
                key: ""
            };

            scope.stopProp = function (e) {
                e.stopPropagation();
            }

            var delField = function (type, field_) {
                var list = scope.fields[type];
                for (var i = 0; i < list.length; i++) {
                    if (field_.columnId === list[i].columnId) {
                        list.splice(i, 1);
                        break;
                    }
                }
            }

            $rootScope.getDimensionality = function () {
                var res = [];
                angular.forEach(scope.fields.dimensionality, function (dim) {
                    if (dim.isShow) {
                        res.push(dim);
                    }
                });
                return res;
            }

            $rootScope.getMeasurement = function () {
                var res = [];
                angular.forEach(scope.fields.measurement, function (dim) {
                    if (dim.isShow) {
                        res.push(dim);
                    }
                });
                return res;
            }

            scope.$watch('fields.key', function (newV, oldV) {
                if (!newV) {
                    for (var i in scope.fields) {
                        if (scope.fields[i] instanceof Array) {
                            angular.forEach(scope.fields[i], function (field) {
                                field.shown_for_search = true;
                            });
                        }
                    }
                    return;
                }

                for (var i in scope.fields) {
                    if (scope.fields[i] instanceof Array) {
                        angular.forEach(scope.fields[i], function (field) {
                            if (field.columnDesc.indexOf(newV) != -1) {
                                field.shown_for_search = true;
                            } else {
                                field.shown_for_search = false;
                            }
                        });
                    }
                }
            });

            scope.dimensionality2_fields_shown = false;
            scope.dimensionality_fields_shown = true;
            scope.measurement2_fields_shown = false;
            scope.measurement_fields_shown = true;
            scope.condition_fields_shown = true;

            scope.dimensionality_name = '维度字段';
            scope.dimensionality2_name = '纬度字段';
            scope.measurement2_name = '气泡大小';
            scope.measurement_name = '度量字段';

            var charts = [
                'StandardPieChart',
                'StandardLineChart',
                'StandardBarChart',
                'StandardRadarChart',
                'StandardScatterchart',
                'SpeedometerInstrumentChart'
            ];
            var sheets = [
                'summarytab',
                'crosstab',
                'detailtab',
                'retentionrate'
            ];
            var conds = [
                'checkbox',
                'radio',
                'select',
                'between',
                'date'
            ];

            // 获取字段数据
            tools.get({
                url: '/Ibm-Client/getTable.htm',
                data: {
                    tbId: tbId,
                    tableType: tableType,
                    pageId: $routeParams.id
                },
                succ: function (resp) {
                    scope.fields = resp.value;

                    if (!scope.fields) {
                        return;
                    }

                    scope.fields.dimensionality2 = angular.copy(scope.fields.dimensionality);
                    scope.fields.measurement2 = angular.copy(scope.fields.measurement);

                    angular.forEach(scope.fields.dimensionality, function (dim) {
                        dim.shown = true;
                        dim.meaType = 'group';
                        dim.shown_for_search = true;
                        dim.fieldType = "dimensionality";
                        dim.fieldId = tools.fieldId();

                        dim.beginEdit = function () {
                            $rootScope.$broadcast('INPUT_EDIT_EV', dim.columnDesc, function (content) {
                                dim.columnDesc = content;
                                tools.get({
                                    url: '/Ibm-Client/updateColumn.htm',
                                    data: {
                                        tableType: $routeParams.tableType,
                                        columnDesc: dim.columnDesc,
                                        tbId: $routeParams.tbId,
                                        columnId: dim.columnId
                                    },
                                    succ: function (resp) {
                                        if (resp.success) {
                                            $timeout(function () {
                                                // 更新组件上的字段
                                                angular.forEach(scope.fields.condition, function (cond) {
                                                    if (cond.columnId == dim.columnId) {
                                                        $timeout(function () {
                                                            cond.columnDesc = dim.columnDesc;
                                                        }, 0);
                                                    }
                                                });

                                                // 更新编辑区的图标数据
                                                $rootScope.$broadcast('UPDATE_CHART_EV', dim.columnId, dim.columnDesc);
                                                $rootScope.$broadcast('UPDATE_SHEET_EV', dim.columnId, dim.columnDesc);
                                                $rootScope.$broadcast('UPDATE_COND_EV', dim.columnId, dim.columnDesc);
                                            }, 0);
                                        }
                                    }
                                });
                            });
                        }
                    });

                    angular.forEach(scope.fields.dimensionality2, function (dim) {
                        dim.shown = true;
                        dim.meaType = 'group';
                        dim.shown_for_search = true;
                        dim.fieldType = "dimensionality2";
                        dim.fieldId = tools.fieldId();
                    });

                    angular.forEach(scope.fields.measurement, function (mea) {
                        mea.shown = true;
                        mea.meaType = 'sum';

                        if (mea.columnDesc == '好评率' || mea.columnDesc == '差评率') {
                            mea.meaType = 'avg';
                        }

                        mea.shown_for_search = true;
                        mea.fieldType = "measurement";
                        mea.fieldId = tools.fieldId();

                        mea.beginEdit = function () {
                            $rootScope.$broadcast('INPUT_EDIT_EV', mea.columnDesc, function (content) {
                                mea.columnDesc = content;

                                tools.get({
                                    url: '/Ibm-Client/updateColumn.htm',
                                    data: {
                                        tableType: $routeParams.tableType,
                                        columnDesc: mea.columnDesc,
                                        tbId: $routeParams.tbId,
                                        columnId: mea.columnId
                                    },
                                    succ: function (resp) {
                                        if (resp.success) {
                                            $timeout(function () {
                                                // 更新组件上的字段
                                                angular.forEach(scope.fields.condition, function (cond) {
                                                    if (cond.columnId == mea.columnId) {
                                                        $timeout(function () {
                                                            cond.columnDesc = mea.columnDesc;
                                                        }, 0);
                                                    }
                                                });

                                                // 更新编辑区的图标数据
                                                $rootScope.$broadcast('UPDATE_CHART_EV', mea.columnId, mea.columnDesc);
                                                $rootScope.$broadcast('UPDATE_SHEET_EV', mea.columnId, mea.columnDesc);
                                                $rootScope.$broadcast('UPDATE_COND_EV', mea.columnId, mea.columnDesc);
                                            }, 0);
                                        }
                                    }
                                });
                            });
                        }
                    });

                    angular.forEach(scope.fields.measurement2, function (mea) {
                        mea.shown = true;
                        mea.meaType = 'sum';
                        mea.shown_for_search = true;
                        mea.fieldType = "measurement2";
                        mea.fieldId = tools.fieldId();
                    });

                    angular.forEach(scope.fields.condition, function (cond) {
                        cond.shown = true;
                        cond.fieldType = "condition";
                        cond.shown_for_search = true;
                        cond.fieldId = tools.fieldId();
                    });

                    $timeout(function () {
                        $(element).find('.field_menu').dropdown({
                            action: 'none',
                            delay: {
                                hide: 5000
                            }
                        });
                        $(element).find('section').height(document.documentElement.clientHeight - 140).mCustomScrollbar({
                            theme: "minimal-dark"
                        });
                    }, 50);
                }
            });

            // 监听度量删除事件并恢复字段
            events.MEASURE_REDUCE_EV_OFF = $rootScope.$on('MEASURE_REDUCE_EV', function (e, columnId) {
                angular.forEach(scope.fields.measurement, function (mea) {
                    if (mea.columnId == columnId) {
                        mea.shown = true;
                    }
                });
            });

            // 监听度量2删除事件并恢复字段
            events.MEASURE2_REDUCE_EV_OFF = $rootScope.$on('MEASURE2_REDUCE_EV', function (e, columnId) {
                angular.forEach(scope.fields.measurement2, function (mea) {
                    if (mea.columnId == columnId) {
                        mea.shown = true;
                    }
                });
            });

            // 监听维度删除事件
            events.DIMENSION_REDUCE_EV_OFF = $rootScope.$on('DIMENSION_REDUCE_EV', function (e, columnId) {
                angular.forEach(scope.fields.dimensionality, function (dim) {
                    if (dim.columnId == columnId) {
                        dim.shown = true;
                    }
                });
            });

            // 监听维度2删除事件
            events.DIMENSION_2_REDUCE_EV_OFF = $rootScope.$on('DIMENSION2_REDUCE_EV', function (e, columnId) {
                angular.forEach(scope.fields.dimensionality2, function (dim) {
                    if (dim.columnId == columnId) {
                        dim.shown = true;
                    }
                });
            });

            // 监听组件字段删除事件
            events.CONDITION_REDUCE_EV_OFF = $rootScope.$on('CONDITION_REDUCE_EV', function (e, columnId) {
                angular.forEach(scope.fields.condition, function (cond) {
                    if (cond.columnId == columnId) {
                        cond.shown = true;
                    }
                });
            });

            // 监听分类字段的删除和恢复事件
            events.RECOVER_CLASSFIES_FIELD_OFF = $rootScope.$on('RECOVER_CLASSFIES_FIELD', function (e, flag, columnId) {
                angular.forEach(scope.fields.dimensionality, function (dim) {
                    if (dim.columnId == columnId) {
                        dim.shown = flag;
                    }
                });
            });

            // 监听图的字段的恢复事件
            events.FIELD_RECOVER_FROM_CHART_EV_OFF = $rootScope.$on('FIELD_RECOVER_FROM_CHART_EV', function (e, dimensions,dimensions2, measures, measures2, classifies, type) {
                $timeout(function () {
                    scope.dimensionality_name = '维度字段';
                    scope.measurement_name = '度量字段';
                    if (type == 'bubble') {
                        scope.dimensionality2_fields_shown = false;
                        scope.dimensionality_fields_shown = true;
                        scope.measurement2_fields_shown = true;
                        scope.measurement_fields_shown = true;
                        scope.condition_fields_shown = false;
                    }
                    else if (type == 'funnel') {
                        scope.dimensionality2_fields_shown = false;
                        scope.dimensionality_fields_shown = false;
                        scope.measurement2_fields_shown = false;
                        scope.measurement_fields_shown = true;
                        scope.condition_fields_shown = false;
                    } 
                    else if(type == 'heatmap'){
                        scope.dimensionality2_fields_shown = true;
                        scope.dimensionality_fields_shown = true;
                        scope.measurement_fields_shown = true;
                        scope.condition_fields_shown = false;
                        scope.measurement2_fields_shown = false;
                        scope.dimensionality_name = '经度字段';
                        scope.dimensionality2_name = '纬度字段';
                        scope.measurement_name = '度量字段';
                    }
                    else if(type == 'heatmarketmap'){
                        scope.dimensionality2_fields_shown = true;
                        scope.dimensionality_fields_shown = true;
                        scope.measurement_fields_shown = false;
                        scope.condition_fields_shown = false;
                        scope.measurement2_fields_shown = false;
                        scope.dimensionality_name = '经度字段';
                        scope.dimensionality2_name = '纬度字段';
                    }
                    else {
                        scope.dimensionality2_fields_shown = false;
                        scope.dimensionality_fields_shown = true;
                        scope.measurement2_fields_shown = false;
                        scope.measurement_fields_shown = true;
                        scope.condition_fields_shown = false;
                    }

                    
                }, 0);

                selected_type = type;

                if (dimensions.length == 0 && dimensions2.length == 0 && measures.length == 0 && measures2.length == 0 && classifies.length == 0) {
                    for (var i in scope.fields) {
                        angular.forEach(scope.fields[i], function (field, index) {
                            field.shown = true;
                        });
                    }

                    tools.refresh();
                    return;
                }

                var columnIds = [];
                angular.forEach(dimensions, function (dim) {
                    columnIds.push(dim.columnId);
                });
                angular.forEach(dimensions2, function (dim) {
                    columnIds.push(dim.columnId);
                });
                angular.forEach(measures, function (mea) {
                    columnIds.push(mea.columnId);
                });
                angular.forEach(measures2, function (mea) {
                    columnIds.push(mea.columnId);
                });
                angular.forEach(classifies, function (cla) {
                    columnIds.push(cla.columnId);
                });

                angular.forEach(scope.fields.dimensionality, function (field) {
                    if (columnIds.indexOf(field.columnId) != -1) {
                        $timeout(function () {
                            field.shown = false;
                        }, 0);
                    } else {
                        $timeout(function () {
                            field.shown = true;
                        }, 0);
                    }
                });

                angular.forEach(scope.fields.dimensionality2, function (field) {
                    if (columnIds.indexOf(field.columnId) != -1) {
                        $timeout(function () {
                            field.shown = false;
                        }, 0);
                    } else {
                        $timeout(function () {
                            field.shown = true;
                        }, 0);
                    }
                });

                angular.forEach(scope.fields.measurement, function (field) {
                    if (columnIds.indexOf(field.columnId) != -1) {
                        $timeout(function () {
                            field.shown = false;
                        }, 0);
                    } else {
                        $timeout(function () {
                            field.shown = true;
                        }, 0);
                    }
                });

                angular.forEach(scope.fields.measurement2, function (field) {
                    if (columnIds.indexOf(field.columnId) != -1) {
                        $timeout(function () {
                            field.shown = false;
                        }, 0);
                    } else {
                        $timeout(function () {
                            field.shown = true;
                        }, 0);
                    }
                });
            });

            // 监听表的字段的恢复事件
            events.FIELD_RECOVER_FROM_SHEET_EV_OFF = $rootScope.$on('FIELD_RECOVER_FROM_SHEET_EV', function (e, lineFieldNames, listFieldNames, dataFieldNames, type) {
                selected_type = type;

                switch (type) {
                    case 'summarytab':
                        $timeout(function () {
                            scope.dimensionality2_fields_shown = false;
                            scope.dimensionality_fields_shown = true;
                            scope.measurement_fields_shown = true;
                            scope.condition_fields_shown = false;

                            scope.dimensionality_name = '表头字段';
                            scope.measurement_name = '汇总字段';
                        }, 0);
                        break;

                    case 'crosstab':
                        $timeout(function () {
                            scope.dimensionality2_fields_shown = true;
                            scope.dimensionality_fields_shown = true;
                            scope.measurement_fields_shown = true;
                            scope.condition_fields_shown = false;

                            scope.dimensionality_name = '行表头字段';
                            scope.dimensionality2_name = '列表头字段';
                            scope.measurement_name = '汇总字段';
                        }, 0);
                        break;

                    case 'detailtab':
                        $timeout(function () {
                            scope.dimensionality2_fields_shown = false;
                            scope.dimensionality_fields_shown = true;
                            scope.measurement_fields_shown = true;
                            scope.condition_fields_shown = false;

                            scope.dimensionality_name = '维度字段';
                            scope.measurement_name = '度量字段';
                        }, 0);
                        break;
                    case 'retentionrate':
                        $timeout(function () {
                            scope.dimensionality2_fields_shown = true;
                            scope.dimensionality_fields_shown = true;
                            scope.measurement_fields_shown = false;
                            scope.condition_fields_shown = false;

                            scope.dimensionality_name = '日期';
                            scope.dimensionality2_name = '用户标志';
                            // scope.measurement_name = '度量字段';
                        }, 0);
                        break;
                }

                if (lineFieldNames.length == 0 && listFieldNames.length == 0 && dataFieldNames.length == 0) {
                    angular.forEach(scope.fields.dimensionality, function (dim) {
                        dim.shown = true;
                    });
                    angular.forEach(scope.fields.dimensionality2, function (dim) {
                        dim.shown = true;
                    });
                    angular.forEach(scope.fields.measurement, function (mea) {
                        mea.shown = true;
                    });
                    return;
                }

                var columnIds = [];

                // 隐藏行表头,明细表的lineFieldNames包含维度和度量
                angular.forEach(lineFieldNames, function (field) {
                    columnIds.push(field.columnId);
                });
                angular.forEach(scope.fields.dimensionality, function (field) {
                    if (columnIds.indexOf(field.columnId) != -1) {
                        $timeout(function () {
                            field.shown = false;
                        }, 0);
                    } else {
                        $timeout(function () {
                            field.shown = true;
                        }, 0);
                    }
                });
                if (type == 'detailtab') {
                    angular.forEach(scope.fields.measurement, function (field) {
                        if (columnIds.indexOf(field.columnId) != -1) {
                            $timeout(function () {
                                field.shown = false;
                            }, 0);
                        } else {
                            $timeout(function () {
                                field.shown = true;
                            }, 0);
                        }
                    });
                }

                // 隐藏列表头
                columnIds.length = 0;
                angular.forEach(listFieldNames, function (field) {
                    columnIds.push(field.columnId);
                });
                angular.forEach(scope.fields.dimensionality2, function (field) {
                    if (columnIds.indexOf(field.columnId) != -1) {
                        $timeout(function () {
                            field.shown = false;
                        }, 0);
                    } else {
                        $timeout(function () {
                            field.shown = true;
                        }, 0);
                    }
                });

                // 如果是明细表的话所有的字段都存放在维度中,所以以下这一步就不用了
                if (type == 'detailtab') {
                    return;
                }

                columnIds.length = 0;
                angular.forEach(dataFieldNames, function (field) {
                    columnIds.push(field.columnId);
                });
                angular.forEach(scope.fields.measurement, function (field) {
                    if (columnIds.indexOf(field.columnId) != -1) {
                        $timeout(function () {
                            field.shown = false;
                        }, 0);
                    } else {
                        $timeout(function () {
                            field.shown = true;
                        }, 0);
                    }
                });
            });

            // 监听组件的字恢复事件
            events.FIELD_RECOVER_FROM_COND_EV_OFF = $rootScope.$on('FIELD_RECOVER_FROM_COND_EV', function (e, field, type) {
                selected_type = type;

                $timeout(function () {
                    scope.dimensionality2_fields_shown = false;
                    scope.dimensionality_fields_shown = false;
                    scope.measurement_fields_shown = false;
                    scope.condition_fields_shown = true;
                }, 0);

                if (!field) {
                    angular.forEach(scope.fields.condition, function (condField) {
                        condField.shown = true;
                    });
                    return;
                }

                angular.forEach(scope.fields.condition, function (condField) {
                    if (condField.columnId == field.columnId) {
                        condField.shown = false;
                    } else {
                        condField.shown = true;
                    }
                });
            });

            // 起飞
            scope.fly = function (e, type, index) {
                if (!$rootScope.someSheetSelected() && !$rootScope.someChartSelected() && !$rootScope.someConditionSelected() && !$rootScope.someMapSelected()) {
                    return tools.msg("请选择一个图或者表再进行操作");
                }
                var off = $(e.target).offset();

                // 如果是明细表的话,x和Y坐标合为一体,所以统一向x飞去
                var origin_type = type;
                if (selected_type == 'detailtab') {
                    type = 'dimensionality';
                }

                if ($('.field-manager-' + type + '> .dropdown:last').size()) {
                    var end_ele = $('.field-manager-' + type + '>.dropdown:last');
                } else {
                    var end_ele = $('.field-manager-' + type);
                }

                var end = {
                    left: end_ele.offset().left + 40,
                    top: end_ele.offset().top
                };
                var begin = {
                    left: off.left,
                    top: off.top
                };
                $rootScope.$broadcast('FLY_EV', begin, end, type, scope.fields[origin_type][index]);
                scope.fields[origin_type][index].shown = false;
            }

            // 新建筛选
            scope.createFilter = function (type) {

            }

            // 隐藏字段
            scope.hideField = function (field) {
                tools.get({
                    url: '/Ibm-Client/updateColumn.htm',
                    data: {
                        tableType: $routeParams.tableType,
                        tbId: $routeParams.tbId,
                        columnId: field.columnId,
                        isShow: false
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            field.isShow = false;
                        }
                    }
                });
            }

            scope.editFieldName = function (fname) {
                $rootScope.$broadcast('INPUT_EDIT_EV', fname, function (content) {
                    if (!content) {
                        return;
                    }
                });
            }

            scope.changeAsMeasure = function (isDimension, field) {
                tools.get({
                    url: '/Ibm-Client/updateColumn.htm',
                    data: {
                        tableType: $routeParams.tableType,
                        tbId: $routeParams.tbId,
                        columnId: field.columnId,
                        isDimension: isDimension,
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            if (isDimension) {
                                field.fieldType = 'dimensionality';
                                field.meaType = 'group';
                                field.isDimension = true;
                                delField('measurement', field);
                                scope.fields.dimensionality.push(field);
                            } else {
                                field.fieldType = 'measurement';
                                field.meaType = 'sum';
                                field.isDimension = false;
                                delField('dimensionality', field);
                                scope.fields.measurement.push(field);
                            }
                        }
                    }
                });
            }

            scope.$on('$destroy', function () {
                for (var i in events) {
                    if (i.indexOf('_OFF') != -1) {
                        events[i]();
                    }
                }
            });

            var cur_show_ctx_field = null;
            var menus = [
                {
                    name: '转换为度量',
                    icon: '',
                    fn: function () {
                        if (!cur_show_ctx_field) {
                            return;
                        }
                        scope.changeAsMeasure(cur_show_ctx_field.fieldType === "dimensionality" ? false : true, cur_show_ctx_field);
                        cur_show_ctx_field = null;
                    }
                },
                {
                    name: '隐藏字段',
                    icon: '',
                    fn: function () {
                        if (!cur_show_ctx_field) {
                            return;
                        }
                        scope.hideField(cur_show_ctx_field);
                        cur_show_ctx_field = null;
                    }
                },
                {
                    name: '重命名',
                    icon: '',
                    fn: function () {
                        cur_show_ctx_field.beginEdit();
                    }
                },
                {
                    name: '分组'
                }
            ];

            scope.showContext = function (e, field) {
                e.stopPropagation();

                if (cur_show_ctx_field === field) {
                    cur_show_ctx_field = null;
                    return $rootScope.$on('CONTEXTMENU_OFF_EV');
                }
                cur_show_ctx_field = field;
                if (cur_show_ctx_field.fieldType == 'dimensionality') {
                    menus[0].name = '转换为度量';
                } else {
                    menus[0].name = '转换为维度';
                }
                $rootScope.$broadcast('CONTEXTMENU_EV', e.pageX, e.pageY, menus);
            }
        },
        templateUrl: "/trend-new-BI/app/components/editor/fieldList/fieldListView.html"
    }
}]);